<?php

namespace App\Http\Middleware;

use App\Tool\Helper;
use Closure;

class CheckWechatToken
{
    protected $except = [
        'index',
        'index-doctor',
        'doctor',
        'mechanism',
        'about-problem',
        'about-me',
        'integral-rule',
        'department',
        'article',
        'article-category',
        'article-detail'
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->handelExcept($request)) {
            return $next($request);
        }

        if (!auth('wechat')->check()) {
            // 未登录
            return $this->writeJson(401, null, '请先登录', 401);
        }

        $user = auth('wechat')->user();
        if ($user['status'] != 1) {
            return $this->writeJson(403, null, '账号已被禁用！');
        }

        return $next($request);
    }

    protected function writeJson($code = 0, $result = null, $msg = null, $status = 200)
    {
        return Helper::writeJson($code, $result, $msg, $status);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    private function handelExcept($request)
    {
        $uri = $request->getPathInfo();
        $uri = substr($uri, 8);

        if (in_array($uri, $this->except)) {
            return true;
        } else {
            return false;
        }
    }
}
